package org.yylnb.openplatform.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.yylnb.openplatform.commons.utlis.CommonsResult;
import org.yylnb.openplatform.gateway.api.CacheService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 判断用户是否携带了系统需要参数
 *
 * @author RainLin
 * @date 2020/7/24 - 13:32
 */
@Component
public class SystemParamsFilter extends ZuulFilter {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CacheService cacheService;
    private static final Logger LOGGER = LoggerFactory.getLogger(SystemParamsFilter.class);

    /**
     * API系统参数
     */
    private static final String API_SYSTEM_PARAMETERS = "API_SYSTEM_PARAMETERS";

    @Override
    public String filterType() {
        //前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 50;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取上下文信息
        RequestContext context = RequestContext.getCurrentContext();
        //我们要求的是什么,我们可以保存到redis中,实现实时变化
        CommonsResult<List<String>> commonsResult = cacheService.sGet(API_SYSTEM_PARAMETERS);
        //获取到我们要求传递的参数
        List<String> parameters = commonsResult.getData();
        LOGGER.error("查询到的系统参数列表是:{}", parameters);

        //获取到这个参数用户传递的值
        HttpServletRequest request = context.getRequest();
        for (String parameter : parameters) {
            //从用户发来的参数集合中寻找
            String value = request.getParameter(parameter);
            if (StringUtils.isEmpty(value)) {
                //没有找到
                context.setSendZuulResponse(false);
                HttpServletResponse response = context.getResponse();
                response.setContentType("application/json;charset=utf-8");
                try {
                    context.setResponseBody(objectMapper.writeValueAsString("没有传递" + parameter + "参数"));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        return null;
    }
}

